/*
 * @Author: yangzonglong
 * @Date: 2021-05-12 11:04:09
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-09-01 17:04:13
 * @Auditor: 
 */
import { ControlProps } from './../components/fd/interface';
import { flatControl } from './../components/fd/util';
import { FormField, FormProps } from './../interface';

export default function (form: FormProps, all?: boolean): FormField[] {
  if (!form) return [];
  let list: FormField[] = [];

  if (form.formEngine === 'GFORM') {
    const content = form.content ? JSON.parse(form.content) : {};

    if (all) {
      content.list = flatControl(content.list);

      content.list.forEach((item: ControlProps) => {

        list.push({
          fieldName: item.options?.formItemProps?.name || item.id,
          controlId: item.id,
          name: item.options?.formItemProps?.label,
          options: item?.options,
          type: item.type
        })

        // table 需要把 column也push进去
        if (item.type === 'table') {
          const columns = item.options?.tableProps?.columns;

          columns.forEach((column: Record<string, string>) => {
            list.push({
              fieldName: item.id + '#' + column.dataIndex,
              controlId: item.id + '#' + column.dataIndex,
              name: column.title,
              type: 'column'
            })
          })
        }
      })
    } else {
      content.list = flatControl(content.list);
      
      // 排除无效的，name 不存在则认为无效
      const filter = content.list.filter((item: ControlProps) => item.options?.formItemProps?.name);

      list = filter.map((item: ControlProps) => {
        return {
          fieldName: item.options?.formItemProps?.name,
          controlId: item.id,
          name: item.options?.formItemProps?.label,
          type: item.type
        }
      })
    }
  }

  if (form.formEngine === 'LFORM') {
    // 匹配正常闭合的标签
    const match = form.content.match(/<.*?>/g);
    match?.forEach((item: string) => {
      const keyMatch = item.match(/key=".*?"/g);
      const valueMatch = item.match(/title=".*?"/g);
      const typeMatch = item.match(/orgtype=".*?"/g);
      if (keyMatch) {
        const keyStr = keyMatch[0].split('=')[1];
        const nameStr = valueMatch ? valueMatch[0].split('=')[1] : '';
        const typeStr = typeMatch ? typeMatch[0].split('=')[1] : '';
        list.push({
          fieldName: keyStr.replace(/"/g, ''),
          controlId: keyStr.replace(/"/g, ''),
          name: nameStr.replace(/"/g, ''),
          type: typeStr.replace(/"/g, '')
        })
      }
    })
  }
  for (let i of list) {
    i.options = JSON.stringify(i.options) || '{}'
  }
  return list
}